from flask import Flask, render_template, request, session, redirect, url_for

from project.connect_db import con_my_sql
from project.index_services import views
from project.user_page import user_page
from project.engineer_page import engineer_page

app = Flask(__name__)

# 导入路由跳转文件，并添加同一的路由地址前缀
app.register_blueprint(views, url_prefix='/page_service')
app.register_blueprint(user_page, url_prefix='/user_page')
app.register_blueprint(engineer_page, url_prefix='/engineer_page')

app.secret_key = '123456'

# 对于需要登录才能访问的界面使用：
@app.route("/user_center")
def user_center():
    # 检查用户是否登录
    if not session.get('logged_in'):
        # 未登录时重定向到登录页，并传递当前URL作为next参数
        return redirect(url_for('login', next=request.url))
    
    # 已登录用户的正常页面逻辑
    return render_template("user_center.html")

# 主界面渲染
@app.route('/')
def index():
    return render_template('index.html')

# 登录页面渲染
@app.route('/login')
def index_login():
    return render_template('login.html')

# 登陆功能实现
@app.route("/login", methods=["GET", "POST"])
def login():
    username = request.form.get("username")
    password = request.form.get("password")

    # 检验是否为普通用户的账号
    code = "SELECT * FROM users_info where username = '%s'" % username
    cursor_ans = con_my_sql(code)
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        if password == cursor_select[0]['password']:
            session['logged_in'] = True
            session.modified = True
            session['username'] = username
            # 固定跳转到首页
            return redirect(url_for('index'))  # 关键修改点
        else:
            return "密码错误"

    # 检验是否为维修人员的账号
    code = "SELECT * FROM engineers_info where engineer_name = '%s'" % username
    cursor_ans = con_my_sql(code)
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        if password == cursor_select[0]['password']:
            session['logged_in'] = True
            session.modified = True
            session['username'] = username
            # 固定跳转到首页
            return redirect(url_for('index'))  # 关键修改点
        else:
            return "密码错误"

    return "用户不存在"

# 退出登录功能实现
@app.route('/logout')
def index_logout():
    session.clear()
    session.modified = True
    return redirect(url_for('index'))

# 注册页面渲染
@app.route('/register')
def index_register():
    return render_template('register.html')

# 注册功能实现
@app.route("/register", methods = ["POST"])
def register():
    username = request.form.get("username")
    password = request.form.get("password")
    password2 = request.form.get("password2")

    # 不能和已注册的用户名相同
    code = "SELECT * FROM users_info where username = '%s'" % username
    # 返回的是列表
    cursor_ans = con_my_sql(code)
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        return "用户已存在"

    # 不能和维修人员的用户名相同
    code = "SELECT * FROM engineers_info where username = '%s'" % username
    cursor_ans = con_my_sql(code)
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        return "用户已存在"


    if password != password2:
        return "密码不一致"

    code = "INSERT INTO users_info (username, password) VALUES ('%s', '%s')" % (username, password)
    con_my_sql(code)

    return redirect(url_for('index_login'))

@app.route("/user_page")
def user_page():
    return render_template("home.html")

@app.route("/engineer_page")
def engineer_page():
    return render_template("engineer_console.html")

@app.route("/select_page")
def select_page():
    username = session.get('username')

    code = "SELECT * FROM users_info WHERE username = '%s'" % username
    cursor_ans = con_my_sql(code)
    cursor_select = cursor_ans.fetchall()

    if len(cursor_select) > 0:
        return render_template("home.html")
    else:
        return render_template("engineer_console.html")


if __name__ == '__main__':
    app.run(debug = True)
